#include <stdio.h>
#include "ParameterManager.h"
#include "ParaConfig.h"
#include "esp_err.h"
#include "nvs.h"
#define NAMESPACE "config"

static const char * TAG = "Para manager";

ConfigList g_ParaList = {0}; //参数静态实例
uint8_t MapResult[100] = {0}; //映射表静态实例

esp_err_t init_parameters_manager(void){
        // 初始化NVS
    esp_err_t ret = init_nvs();
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to initialize NVS: %s", esp_err_to_name(ret));
        return ESP_FAIL;
    }
    return ESP_OK;
}


esp_err_t load_all_parameters(void) {
    
    esp_err_t ret1, ret2;
    bool load_success = true;
    
    ESP_LOGI(TAG, "Loading parameters from NVS...");
    
    // 加载参数表
    ret1 = load_struct_from_nvs(NAMESPACE, "para_list", &g_ParaList, sizeof(g_ParaList));
    if (ret1 != ESP_OK) {
        ESP_LOGW(TAG, "Failed to load parameter list: %s", esp_err_to_name(ret1));
        load_success = false;
    } else {
        ESP_LOGI(TAG, "Parameter list loaded successfully");
    }
    
    // 加载映射表
    int loaded_count = load_array_from_nvs(NAMESPACE, "map_result", MapResult, sizeof(uint8_t), sizeof(MapResult));
    if (loaded_count == sizeof(MapResult)) {
        ESP_LOGI(TAG, "Map result loaded successfully, count: %d", loaded_count);
    } else {
        ESP_LOGW(TAG, "Failed to load map result, count: %d", loaded_count);
        load_success = false;
    }
    
    if (!load_success) {
        ESP_LOGI(TAG, "Using default parameters");
        // 保存默认参数到NVS以便下次使用
        if(save_struct_to_nvs("config", "para_list", &g_ParaList, sizeof(g_ParaList))!=ESP_OK){
            ESP_LOGW(TAG, "Failed to save para_list");
        }
        if(save_struct_to_nvs("config", "map_result", &MapResult, sizeof(MapResult))!=ESP_OK){
            ESP_LOGW(TAG, "Failed to save map_result");
        }
        return ESP_FAIL;
    }
    
    ESP_LOGI(TAG, "All parameters loaded successfully");
    return ESP_OK;
}
esp_err_t save_all_parameters(void){
        ESP_LOGI(TAG, "Save parameter\n");
        // 保存默认参数到NVS以便下次使用
        if(save_struct_to_nvs("config", "para_list", &g_ParaList, sizeof(g_ParaList))!=ESP_OK){
            ESP_LOGW(TAG, "Failed to save para_list");
        }
        if(save_struct_to_nvs("config", "map_result", &MapResult, sizeof(MapResult))!=ESP_OK){
            ESP_LOGW(TAG, "Failed to save map_result");
        }
        return ESP_OK;
}
//